package com.ncmmall.api.apis.mall;


import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.params.GoodsCollectDTO;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.goods.GoodsCollectApplication;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.collect.GoodsCollect;
import com.ncmmall.domain.business.goods.collect.QGoodsCollect;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品收藏接口
 *
 * @author likaikai
 * @date 2019-07-15 11:58:06
 */
@RestController
@RequestMapping(value = "/goods/collect")
@Component
public class GoodsCollectApi {

    private Logger logger = LoggerFactory.getLogger(GoodsCollectApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Value("${store.domain}")
    private String storeDomain;

    @Autowired
    private GoodsCollectApplication goodsCollectApplication;

    /**
     * 商品收藏列表
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(HttpServletRequest request, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize) {
        Result result = new Result();
        try {

            WebUser member = Securitys.user(request);

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            QueryPage<GoodsCollect> page = queryChannelService.findPage("select c from GoodsCollect c where c.member.id = :mid", pageRequest.setParams(ImmutableMap.of("mid", member.getId())), GoodsCollect.class);

            List<Map<String, Object>> list = new ArrayList<>(page.getResult().size());
            for (GoodsCollect goodsCollect : page.getResult()) {
                Map<String, Object> map = new LinkedHashMap<>();

                Goods goods = goodsCollect.getGoods();
                map.put("goodsId", goods.getId());
                map.put("name", goods.getName());
                map.put("status", goods.getStatus());
                map.put("image", StringUtils.isBlank(goods.getDefaultImage()) ? "" : storeDomain + "/uploads/" + goods.getDefaultImage());
                map.put("defaultPrice", goods.getDefaultPrice());
                map.put("marketPrice", goods.getMarketPrice());
                list.add(map);
            }

            return result.ok().inject(new QueryPage<>(page.getTotalCount(), list, pageNo, pageSize));

        } catch (Exception e) {

            logger.error("[获取商品收藏列表异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


    /**
     * 商品收藏
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Result create(HttpServletRequest request, @RequestBody GoodsCollectDTO params) {
        Result result = new Result();
        try {

            WebUser member = Securitys.user(request);

            int count = queryChannelService.selectCount("select count(*) from mall_goods_collect where member_id = :mid and goods_id = :gid", ImmutableMap.of("mid", member.getId(), "gid", params.getGoodsId()));

            if (count > 0) {
                return result.fail().setMsg("请不要重复收藏");
            }

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getGoodsId()), Goods.class);
            if (goods == null) {
                return result.fail().setMsg("商品不存在");
            }

            GoodsCollect goodsCollect = new GoodsCollect();
            goodsCollect.setGoods(goods);
            goodsCollect.setMember(member);

            goodsCollectApplication.create(goodsCollect);

            return result.ok();

        } catch (Exception e) {

            logger.error("[收藏商品异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


    /**
     * 取消商品收藏
     *
     * @param params
     * @param goodsId 商品id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Result remove(HttpServletRequest request, long goodsId) {
        Result result = new Result();
        try {

            WebUser member = Securitys.user(request);

            GoodsCollect goodsCollect = queryChannelService.findOne(QGoodsCollect.goodsCollect.member.id.eq(member.getId()).and(QGoodsCollect.goodsCollect.goods.id.eq(goodsId)), GoodsCollect.class);

            if (goodsCollect == null) {
                return result.fail().setMsg("商品错误");
            }

            goodsCollectApplication.remove(goodsCollect);
            return result.ok();

        } catch (Exception e) {

            logger.error("[取消收藏商品异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


}
